// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router/routes'
import CurrUser from './components/Global/CurrUser'
import GlobalData from './components/Global/GlobalData'
import TimeTools from './components/Tools/TimeTools'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import VueResource from 'vue-resource'
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
import echarts from 'echarts'
import VueSocketIO from 'vue-socket.io'
import RoleTools from './components/Tools/RoleTools'
import VueClipBoard from 'vue-clipboard2'
import SafiAdmin from 'safi-admin'
import 'safi-admin/safi-admin.css'
import Captcha from 'tinydev-slider-captcha'
import 'tinydev-slider-captcha/tinydev-slider-captcha.css'
import AesUtils from './components/Tools/AesUtils'
import SignUtil from './components/Tools/SignUtil'

Vue.use(Captcha)
Vue.use(SafiAdmin)
Vue.use(VueClipBoard)

Vue.prototype.$echarts = echarts

// Vue.use(new VueSocketIO({
//   debug: false,
//   connection: ApiDoNameSocket,//此处可以使用代理地址,/socket为 http:localhost:8000
// }))

// 图片查看
Vue.use(Viewer, {
  defaultOptions: {
    zIndex: 9999
  }
})

Vue.use(ElementUI, {
  size: 'mini'
})

Vue.prototype.checkExpressNumber = function (value) {
  var mobile = value + ''
  var regExp = /^[a-zA-Z0-9]{5,50}$/
  return regExp.test(mobile)
}

Vue.prototype.checkShopName = function (value) {
  var currStr = value + ''
  var regExp = /^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$/
  return regExp.test(currStr)
}

Vue.prototype.checkContactMobile = function (value) {
  var currStr = value + ''
  var regExp1 = /^((0\d{2,3})-)(\d{7,8})$/
  var regExp2 = /^1[3456789]\d{9}$/
  return regExp1.test(currStr) || regExp2.test(currStr)
}

Vue.prototype.checkUserName = function (value) {
  var currStr = value + ''
  var regExp = /^[a-zA-Z0-9]{2,20}$/
  return regExp.test(currStr)
}

Vue.prototype.checkBankCard = function (value) {
  var currStr = value + ''
  var regExp = /^[0-9]{16,20}$/
  return regExp.test(currStr)
}

CurrUser.checkCache()
Vue.config.productionTip = false
Vue.prototype.CurrUser = CurrUser
Vue.prototype.dict = dict
Vue.prototype.ApiDoNameAuth = ApiDoNameAuth
Vue.prototype.ApiDoNameShop = ApiDoNameShop
Vue.prototype.ApiDoNameCommon = ApiDoNameCommon
Vue.prototype.UploadFileUrl = ApiDoNameCommon + 'File/upload'
Vue.prototype.logoImg = './static/top-logo.png'
Vue.prototype.companyName = '可可商城-店铺系统'
GlobalData.checkCache()
Vue.prototype.GlobalData = GlobalData
Vue.prototype.TimeTools = TimeTools
Vue.use(VueResource)
Vue.MyRequestLoading = {}

Vue.prototype.log = function (n) {
  console.log('--------------------------------- xhDebug ----------------------------------')
  console.log(n)
}

/**
 * 浮点运算修复异常
 * @param n
 * @return {number}
 * @constructor
 */
Vue.prototype.Fixed = function (n) {
  n -= 0
  n = n.toFixed(6)
  return n - 0
}

Vue.prototype.toInt = function (n) {
  if (!n) {
    return 0
  }
  n -= 0
  n = Math.ceil(n)
  return n - 0
}

Vue.prototype.listToArray = function (list) {
  var arr = []
  list.forEach(function (name, index) {
    arr.push({
      id: index,
      name: name,
    })
  })
  return arr
}

Vue.prototype.mapToHttpQuery = function (map) {
  var keys = Object.keys(map)
  var arr = []
  keys.forEach(function (_key, index) {
    var value = map[_key]
    arr.push(_key + '=' + value)
  })
  return arr.join('&')
}

Vue.prototype.mapToArray = function (map) {
  if (!map || typeof map === 'undefined') {
    return []
  }
  var arr = []
  Object.keys(map).forEach(function (key) {
    arr.push({
      id: key,
      name: map[key],
    })
  })
  return arr
}

Vue.prototype.GetRandomStr = function (len) {
  if (!len) {
    len = 32
  }
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  var maxPos = $chars.length
  var str = ''
  for (var i = 0; i < len; i++) {
    str += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return str
}

/**
 * 获取设备ID
 * @param str
 * @return {number}
 * @constructor
 */
Vue.prototype.GetDeviceID = function () {
  var CurrDeviceID = localStorage.getItem('CurrDeviceID')
  if (!CurrDeviceID) {
    CurrDeviceID = AesUtils.Encrypt(Vue.prototype.GetRandomStr(32))
    localStorage.setItem('CurrDeviceID', CurrDeviceID)
  }
  return CurrDeviceID
}

/**
 * 数字转为双位: 1 => 01    2 => 02
 * @param n
 * @return {*}
 * @constructor
 * @return {string}
 */
Vue.prototype.ToDouble = function (n) {
  n -= 0
  if (n < 10) {
    return '0' + n
  } else {
    return n
  }
}

/**
 * 是否在数组中
 * @param n
 * @param arr
 */
Vue.prototype.inArray = function (n, arr) {
  var index = -1
  arr.forEach(function (value, key) {
    if (value.toString() === n.toString()) {
      index = key
    }
  })
  return index
}

/**

 * 获取屏幕宽高
 */
Vue.prototype.getWinSize = function () {
  if (document.getElementById('fixed-box') && document.getElementById('fixed-box').offsetHeight > 800) {
    return {
      width: document.getElementById('fixed-box').offsetWidth,
      height: document.getElementById('fixed-box').offsetHeight
    }
  }
  return {
    width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
    height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  }
}

Vue.prototype.getFieldTypeArr = function (field, fieldArr, arrField) {
  var typeArr = []
  fieldArr.forEach(function (value, tmpIndex) {
    if (value.field === field) {
      typeArr = value[arrField]
    }
  })
  return typeArr
}

/**
 * 获取类型1-颜色
 */
Vue.prototype.getTagType = function (key, typeArr) {
  var index = 0
  typeArr.forEach(function (value, tmpIndex) {
    if (value.value === ('' + key)) {
      index = tmpIndex
    }
  })
  var typeArr = ['', 'success', 'warning', 'danger', 'info', '', 'success', 'warning', 'danger', 'info', '', 'success', 'warning', 'danger', 'info']
  return typeArr[index] ? typeArr[index] : ''
}

/**
 * 获取类型2-颜色
 */
Vue.prototype.getTagTextType = function (text, textTypeArr) {
  var index = 0
  textTypeArr.forEach(function (value, tmpIndex) {
    if (value === (text + '')) {
      index = tmpIndex
    }
  })
  var typeArr = ['', 'success', 'warning', 'danger', 'info', '', 'success', 'warning', 'danger', 'info', '', 'success', 'warning', 'danger', 'info']
  return typeArr[index] ? typeArr[index] : ''
}

/**
 * 数字货币
 * @param n
 * @return {*}
 * @constructor
 * @return {string}
 */
Vue.prototype.ToMoney = function (n) {
  n += ''
  var arr = n.split('.')
  if (typeof arr[1] === 'undefined') {
    return n + '.00'
  } else {
    if (arr[1].length === 1) {
      return n + '0'
    } else {
      return n
    }
  }
}

// 应用头部信息
Vue.prototype.getHeader = function (url) {
  const Deviceid = Vue.prototype.GetDeviceID()
  const signObj = SignUtil.generateSign(url, Deviceid)
  return {
    Authorization: 'Bearer ' + this.CurrUser.getToken(),
    Deviceid,
    Platform: 'PC',
    Usertype: 'Shop',
    ...signObj
  }
}

Vue.prototype.validateMoney = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('不能为空'))
  }
  setTimeout(() => {
    if (!Number.parseFloat(value)) {
      callback(new Error('请输入 数字值'))
    } else {
      if (value < 0) {
        callback(new Error('数值类型 必须大于0'))
      } else {
        callback()
      }
    }
  }, 1000)
}

// 表格,数值检查输出
Vue.prototype.getFieldValue = function (map, field) {
  // return '-';
  if (field.indexOf('.') > -1) {
    var fieldArr = field.split('.')
    if (!map[fieldArr[0]]) {
      return '-'
    }
    if (!map[fieldArr[0]][fieldArr[1]]) {
      return '-'
    } else {
      map[fieldArr[0]][fieldArr[1]]
    }
  } else {
    if (!map[field]) {
      return '-'
    } else {
      return map[field]
    }
  }
}

/**
 * 通用请求方法
 * @param url 域名后的接口地址
 * @param params  参数
 * @param callback  正确-回调
 * @param errorCallback  错误-回调
 * @constructor
 */
Vue.prototype.MyRequest = function (url, params, callback, errorCallback, header, isallData) {
  var $this = this
  if (Vue.MyRequestLoading[url] === true) {
    return
  }
  if (!(url.indexOf('http://') > -1 || url.indexOf('https://') > -1)) {
    url = this.ApiDoNameMember + url
  }

  if (typeof params === 'undefined' || params === null) {
    params = {}
  }

  // 判断header参数
  var heaerParams
  if (typeof header === 'undefined' || header === null) {
    // 默认header参数
    heaerParams = this.getHeader(url)
  } else {
    heaerParams = header
  }
  Vue.MyRequestLoading[url] = true
  this.$http.post(url, params, {
    emulateJSON: true,
    credentials: true,
    headers: heaerParams
  }).then(function (response) {
    Vue.MyRequestLoading[url] = false
    var res = response.data
    Vue.MyRequestAllData = res
    if (res.code > 0) {
      // 错误
      if ((res.code === 1001 && res.message === 'token 失效') || res.message === '当前店铺已经禁用') {
        CurrUser.AccessToken = ''
        // CurrUser.IsLogin = false
        CurrUser.setCache(null)
        setTimeout(function () {
          location.reload()
        }, 500)
        return
        //
      } else {
        // 常规错误
        if (typeof errorCallback === 'function') {
          errorCallback(res)
        } else {
          // 常规参数错误
          console.log('常规参数错误' + JSON.stringify(res))
          $this.$message.error(res)
        }
      }
    } else {
      // 正确回调
      if (typeof isallData !== 'undefined' && isallData === true) {
        callback(res)
      } else {
        callback(res.data)
      }
    }
  }, function (errorResponse) {
    Vue.MyRequestLoading[url] = false
    console.error('--------------------------http-请求错误--------------------------')
    console.log(JSON.stringify(errorResponse))
    // $this.$message.error(JSON.stringify(errorResponse))
  })
}

// 提示信息
Vue.prototype.tip = function (message, type) {
  var sitting = {
    message: message ? message.toString() : '操作成功',
    type: type ? type.toString() : 'success'
  }
  this.$message({
    message: sitting.message,
    type: sitting.type,
    center: true,
    duration: 1500
  })
}

// 获取图片: 没有图片设置默认图片
Vue.prototype.getImg = function (url) {
  url = url.toString()
  return url.length > 0 ? url : './static/no-img.png'
}

Vue.prototype.getScrollTop = function () {
  var scrollPos
  if (window.pageYOffset) {
    scrollPos = window.pageYOffset
  } else if (document.compatMode && document.compatMode != 'BackCompat') {
    scrollPos = document.documentElement.scrollTop
  } else if (document.body) {
    scrollPos = document.body.scrollTop
  }
  return scrollPos
}

Vue.prototype.getScrollHeight = function () {
  var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0
  if (document.body) {
    bodyScrollHeight = document.body.scrollHeight
  }
  if (document.documentElement) {
    documentScrollHeight = document.documentElement.scrollHeight
  }
  scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight
  console.log('scrollHeight:' + scrollHeight)
  return scrollHeight
}

Vue.prototype.checkAccessAction = function (accessAction) {
  var currActionList = RoleTools.getActionList()
  // 超级管理员
  if ((currActionList.length === 1 && currActionList[0] === '*') || currActionList === '["*"]') {
    return true
  }
  if (!accessAction) {
    return true
  }
  var actionArr = accessAction.split(',')
  var isAllow = true
  actionArr.forEach(function (action, index) {
    if (currActionList.indexOf(action) === -1) {
      isAllow = false
    }
  })
  return isAllow
}

// 总线程
let bus = new Vue()
Vue.prototype.bus = bus

/* eslint-disable no-new */
var currVueApp = new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>',
  beforeCreate: function () {
    Vue.prototype.bus = this
  },
  mounted () {
    let $this = this
    setTimeout(function () {
      var currUrl = $this.$route.path.substring(1)
      var currUrlItem = window.getNavDataByPath(currUrl)
      var isAccess = $this.checkAccessAction(currUrlItem.action)
      if (!isAccess) {
        $this.$message.warning('当前角色无权限访问')
        $this.$router.push('/')
      }
    }, 3000)
  },
  watch: {
    $route: function (to, from) {
      // console.log('路由变化:', [to.path, from.path])
    }
  }
})

window.showProductDetail = function (type, id) {
  currVueApp.bus.$emit('ShowMessageProductCallBus', type, id)
}
